package BinaryTree;

import java.util.*;

public class BinaryTree {
    static  class  TreeNode{
        public char val;//数据域
        public TreeNode left;//存储左孩子的引用
        public TreeNode right;//存储右孩子的引用
        public TreeNode(char val){
            this.val =val;
        }
    }
    public TreeNode creatTree(){
        TreeNode A = new TreeNode('A');
        TreeNode B = new TreeNode('B');
        TreeNode C = new TreeNode('C');
        TreeNode D = new TreeNode('D');
        TreeNode E = new TreeNode('E');
        TreeNode F = new TreeNode('F');
        TreeNode G = new TreeNode('G');
        TreeNode H = new TreeNode('H');
        A.left = B;
        A.right = C;
        B.left = D;
        B.right =E;
        C.left = F;
        C.right =G;
        E.right = H;
        return A;
    }
    public   int i=0;
    public  TreeNode createTree2(String str){
        TreeNode root =null;
        if(str.charAt(i)!= '#'){
            root = new TreeNode(str.charAt(i));
            i++;
            root.left =createTree2(str);
            root.right =createTree2(str);
        }else{
            i++;
        }
        return root;
    }
    //前序遍历
    public void PreOder(TreeNode root){
        if(root==null){
            return;
        }
        System.out.print(root.val+" ");
        PreOder(root.left);
        PreOder(root.right);
    }
    //oj题
    //给你二叉树的根节点 root ，返回它节点值的 前序 遍历。

    //遍历思路
   // List<Character> list = new ArrayList<>();
    /*public List<Character> preorderTraversal(TreeNode root) {
        if(root==null){
            return list;
        }
        list.add(root.val);
        preorderTraversal(root.left);
        preorderTraversal(root.right);
        return  list;
    }*/
    //子问题
    public List<Character> preorderTraversal2(TreeNode root) {
        List<Character> list = new ArrayList<>();
        if(root==null){
            return list;
        }
        list.add(root.val);
       List<Character> leftTree=preorderTraversal2(root.left);
       list.addAll(leftTree);
       List<Character> rightTree =preorderTraversal2(root.right);
       list.addAll(rightTree);
       return list;

    }
    //中序遍历
    public void InOder(TreeNode root){
        if(root==null){
            return;
        }
        InOder(root.left);
        System.out.print(root.val+" ");
        InOder(root.right);
    }

    //遍历思路
    /*public  List <Character> list =new ArrayList<>();
    public List<Character> inorderTraversal(TreeNode root) {
        if(root==null){
            return list;
        }
        inorderTraversal(root.left);
        list.add(root.val);
        inorderTraversal(root.right);
        return list;
    }*/
    //子问题
   /* public List<Character> inorderTraversal2(TreeNode root) {
        List<Character> list = new ArrayList<>();
        if(root==null){
            return list;
        }
        List<Character> leftTree = inorderTraversal(root.left);
        list.addAll(leftTree);
        list.add(root.val);
        List<Character> rightTree = inorderTraversal(root.right);
        list.addAll(rightTree);
        return list;
    }*/

    //后序遍历
    public void PostOder(TreeNode root){
        if(root==null){
            return;
        }
        PostOder(root.left);
        PostOder(root.right);
        System.out.print(root.val+" ");
    }
    //遍历思路
    public List<Character> list =new ArrayList<>();
    public List<Character> postorderTraversal(TreeNode root) {
        if(root==null){
            return list;
        }
        postorderTraversal(root.left);
        postorderTraversal(root.right);
        list.add(root.val);
        return  list;
    }
    //子问题
    public List<Character> postorderTraversal2(TreeNode root) {
        List<Character> list =new ArrayList<>();
        List <Character> leftTree = postorderTraversal2(root.left);
        list.addAll(leftTree);
        List<Character> rightTree = postorderTraversal2(root.right);
        list.addAll(rightTree);
        list.add(root.val);
        return list;

    }
    //获取树中节点的个数
    public static  int nodeSize =0;
    //遍历二叉树，只要根节点不为空
    public void size(TreeNode root){
        if(root==null){
            return;
        }
        nodeSize++;
        size(root.left);
        size(root.right);
    }

    //子问题 ：整棵树有多少个节点 = 左子树的节点 +右子树节点 +1
    public int size2(TreeNode root){
        if(root==null){
            return 0;
        }
        return size2(root.left )+size2(root.right)+1;
    }


    /*什么是叶子
    root.left==null&&root.right==null
    整棵树的叶子节点 = 左子树的叶子+右子树的叶子
     */
    // 获取叶子节点的个数
    //遍历思路
    public static  int leafSize =0;
    public void getLeafNodeCount(TreeNode root){
        if(root==null){
            return;
        }
        if(root.left==null&&root.right==null){
            leafSize++;
        }
        getLeafNodeCount(root.left);
        getLeafNodeCount(root.right);
    }
    //子问题思路
    public int getLeafNodeCount2(TreeNode root){
        if(root==null){
            return 0;
        }
        if(root.left==null&&root.right==null){
            return 1;
        }
        return getLeafNodeCount2(root.left)+getLeafNodeCount2(root.right);
    }
    //获取K层的节点个数
    public int getKLevelNodeCount(TreeNode root,int k){
        /* k=3 ,
        root左树的k-1层+右树的k-1层

         */
        if(root==null){
            return 0;
        }
        if(k==1){
            return 1;
        }
        return getKLevelNodeCount(root.left,k-1)+getKLevelNodeCount(root.right,k-1);
    }
    //获取二叉树的高度
    public int getHeight(TreeNode root){
        if(root==null){
            return 0;
        }
        int leftHeight = getHeight(root.left);
        int rightHeight = getHeight(root.right);
        return Math.max(leftHeight,rightHeight)+1;
        //return leftHeight>rightHeight ? leftHeight+1 : rightHeight+1;
    }
    //层序遍历
   public  void levelOrder ( TreeNode root){
        if (root==null){
            return;
        }
       Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while(!queue.isEmpty()){
            TreeNode cur = queue.poll();
            System.out.print(cur.val+" ");
            if (cur.left!=null){
                queue.offer(cur.left);
            }
            if (cur.right !=null){
                queue.offer(cur.right);
            }
        }
       System.out.println();
   }

   /*
   时间复杂度：O(N)
   空间复杂度 ：0(logN)
    */
   //检测值为value的元素是否存在
    public TreeNode findVal(TreeNode root,char val){
        if (root==null){
            return null;
        }
        if(root.val==val){
            return  root;
        }
        TreeNode leftT = findVal(root.left,val);
        if (leftT !=null){
            return leftT;
        }
        TreeNode rightT = findVal(root.right,val);
        if (rightT !=null){
            return rightT;
        }
        return null;
    }

   /* 给你两棵二叉树的根节点 p 和 q ，编写一个函数来检验这两棵树是否相同。
    如果两个树在结构上相同，并且节点具有相同的值，则认为它们是相同的。
    */
   public boolean isSameTree(TreeNode p, TreeNode q) {
       //1判断结构是否一样
       if(p!=null && q==null||p==null&&q!=null){
           return false;
       }
       if(p==null&&q==null){
           return true;
       }
       //2.判断值是否一样
       if(p.val!=q.val){
           return false;
       }
       return isSameTree(p.left,q.left)&&isSameTree(p.right,q.right);
   }
   //另一棵的子树
    /*
    root - r, subRoot - s
    时间复杂度 O(r * s)
     */
   public boolean isSubtree(TreeNode root, TreeNode subRoot) {
       if(root==null){
           return true;
       }
       if(isSameTree2(root,subRoot)) return true;
       if(isSubtree(root.left,subRoot)) return true;
       if(isSubtree(root.right,subRoot)) return true;
       return false;
   }
    public boolean isSameTree2(TreeNode p, TreeNode q) {
        //1判断结构是否一样
        if(p!=null && q==null||p==null&&q!=null){
            return false;
        }
        if(p==null&&q==null){
            return true;
        }
        //2.判断值是否一样
        if(p.val!=q.val){
            return false;
        }
        return isSameTree(p.left,q.left)&&isSameTree(p.right,q.right);
    }
   //翻转二叉树
   public TreeNode invertTree(TreeNode root) {
       if(root==null){
           return root;
       }
       if(root.left==null&&root.right==null){
           return root;
       }
       TreeNode tmp =root.left;
       root.left =root.right;
       root.right =tmp;
       invertTree(root.left);
       invertTree(root.right);
       return root;
   }
   //对称二叉树
    //给你一个二叉树的根节点 root ， 检查它是否轴对称。
   public boolean isSymmetric(TreeNode root) {
       if(root==null){
           return true;
       }
       return SymmetricChild(root.left,root.right);
   }
   public boolean SymmetricChild(TreeNode leftTree,TreeNode rightTree){
       if(leftTree!=null&&rightTree==null||leftTree==null&&rightTree!=null){
           return false;
       }
       if(leftTree==null&&rightTree==null){
           return true;
       }
       if(leftTree.val !=rightTree.val){
           return false;
       }
      return SymmetricChild(leftTree.left,rightTree.right)&&SymmetricChild(leftTree.right,rightTree.left);
   }
   //平衡二叉树
    /*
    时间复杂度 O( N*N)
     */
   public boolean isBalanced(TreeNode root) {
       if(root ==null){
           return true;
       }
       int leftHeight = getHeight(root.left);
       int rightHeight = getHeight(root.right);
       return Math.abs(leftHeight-rightHeight)< 2 &&
               isBalanced(root.left)&&isBalanced(root.right);
   }
    public int getHeight2(TreeNode root){
        if(root==null){
            return 0;
        }
        int leftHeight = getHeight2(root.left);
        int rightHeight = getHeight2(root.right);
        return Math.max(leftHeight,rightHeight)+1;
        //return leftHeight>rightHeight ? leftHeight+1 : rightHeight+1;
    }
    //让这题平衡二叉树的时间复杂度从O(N*N) ->  O(N)
    public boolean isBalanced2(TreeNode root) {
        if(root==null)return true;
        return getHeight3(root)>=0;
    }
    public int getHeight3(TreeNode root){
        if(root==null){
            return 0;
        }
        int leftHeight = getHeight3(root.left);
        if(leftHeight<0){
            return  -1;
        }
        int rightHeight = getHeight3(root.right);
        if (rightHeight>=0&&Math.abs(leftHeight-rightHeight)<=1){
            return Math.max(leftHeight,rightHeight)+1;
        }else {
            return -1;
        }
    }
    //二叉搜索树转双向链表
    TreeNode prev =null;
    public  TreeNode Convert(TreeNode pRootOfTree){
       if(pRootOfTree==null){
           return null;
       }
       ConvertChild(pRootOfTree);
       TreeNode head= pRootOfTree;
       if(head.left!=null){
           head = head.left;
       }
       return null;
    }
    public  void ConvertChild(TreeNode root){
        if(root==null){
            return;
        }
        ConvertChild(root.left);
        //打印
        root.left=prev;
        if(prev !=null){
            prev.right =root;
        }
        prev =root;

        ConvertChild(root.right);
    }
    //二叉树遍历
    public List<List<Character>> levelOrder2(TreeNode root) {
        List <List<Character>> ret = new ArrayList<>();
        if(root==null){
            return ret;
        }
        Queue <TreeNode> queue =new LinkedList<>();
        queue.offer(root);
        while(! queue.isEmpty()){
            int size = queue.size();
            List<Character> list = new ArrayList<>();
            while(size !=0){
                TreeNode cur = queue.poll();
                list.add(cur.val);
                //System.out.println(cur.val+" ");
                if(cur.left !=null){
                    queue.offer(cur.left);
                }
                if (cur.right !=null){
                    queue.offer(cur.right);
                }
                size--;
            }
            ret.add(list);
        }
        return ret;
    }
    //判断一棵树是不是完全二叉树
    public boolean isCompleteTree(TreeNode root){
        if (root==null){
            return true;
        }
        Queue <TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while(!queue.isEmpty()){
            TreeNode cur = queue.poll();
            //System.out.println(cur.val+" ");
            if(cur !=null){
                queue.offer(cur.left);
                queue.offer(cur.right);
            }else {
                break;
            }
        }
        while(!queue.isEmpty()){
            TreeNode peek =queue.peek();
            if (peek !=null){
                return false;
            }
            queue.poll();
        }
        return true;
    }
    //求二叉树的最近公共祖先
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root==null){
            return null;
        }
        if(p==root||q==root){
            return root;
        }
        TreeNode leftTree =lowestCommonAncestor(root.left,p,q);
        TreeNode rightTree =lowestCommonAncestor(root.right,p,q);
        if (leftTree !=null&&rightTree !=null){
            return root;
        } else if (leftTree !=null) {
            return leftTree;
        }else {
            return rightTree;
        }
    }
    public  boolean getPath(TreeNode root, TreeNode node, Stack<TreeNode> stack){
        if (root==null){
            return false;
        }
        stack.push(root);
        if (root== node){
            return  true;
        }
        boolean ret =getPath(root.left,node,stack);
        if (ret){
            return true;
        }
        ret = getPath(root.right,node,stack);
        if (ret){
            return true;
        }
        stack.pop();
        return  false;
    }
    public TreeNode lowestCommonAncestor2(TreeNode root, TreeNode p, TreeNode q) {
        if (root==null){
            return  null;
        }
        //1.获取路径上的所有节点
        Stack<TreeNode> stackP = new Stack<>();
        Stack<TreeNode> stackQ = new Stack<>();
        getPath(root,p,stackP);
        getPath(root,q,stackQ);

        //比较两个栈的大小，多的出size个
        int sizeP =stackP.size();
        int sizeQ = stackQ.size();
        if (sizeP>sizeQ){
            int size = sizeP-sizeQ;
            while (size !=0){
                stackP.pop();
                size--;
            }
        }else{
            int size =sizeQ - sizeP;
            while(size !=0){
                stackQ.pop();
                size--;
            }
        }

        //3.每次出数据 看栈顶元素是否一样
        while(! stackP.isEmpty() &&stackQ.isEmpty()) {
            if (stackP.peek()==stackQ.peek()){
                return stackP.peek();
            }else {
                stackP.pop();
                stackQ.pop();
            }
        }
        return null;
    }
    //根据二叉树创建字符串
    public String tree2str(TreeNode root) {
        if(root==null){
            return null;
        }
        StringBuilder stringBuilder = new StringBuilder();
        tree2strChild(root,stringBuilder);
        return stringBuilder.toString();
    }
    public void tree2strChild(TreeNode t,StringBuilder stringBuilder) {
        if (t==null) return ;
        if (t.left !=null){
            stringBuilder.append("(");
            tree2strChild(t.left,stringBuilder);
            stringBuilder.append(")");
        }else{
            if(t.right==null){
                return;
            }else {
                stringBuilder.append("()");
            }
        }
        if (t.right !=null){
            stringBuilder.append("(");
            tree2strChild(t.right,stringBuilder);
            stringBuilder.append(")");
        }else {
            return;
        }
    }
}
